package com.blacktry.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blacktry.entity.model.ApiResult;
import com.blacktry.service.OCRService;
import com.blacktry.utils.ApiResultHandler;
import com.blacktry.utils.HttpUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OCRServiceServiceImpl implements OCRService {
    public ApiResult<List<String>> scanFileByMultipartFile(MultipartFile file) throws Exception {
        List<String> answer = new ArrayList<>();
        String host = "https://ocrapi-advanced.taobao.com";
        String path = "/ocrservice/advanced";
        String method = "POST";
        String appcode = "e7f40ff51eef4fe0b998f88f6f0512c0";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        File fileBuffer = new File("C:\\Users\\asus\\Desktop\\yes.png");
        FileUtils.copyInputStreamToFile(file.getInputStream(),fileBuffer);
        byte[] buffer = new byte[(int)fileBuffer.length()];
        file.getInputStream().read(buffer);
        file.getInputStream().close();
        String base64Code=new BASE64Encoder().encode(buffer);
        String bodys =  "{\"img\":\""+ base64Code+"\",\"prob\":false}";
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            answer = prase(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResultHandler.buildApiResult(200,"成功",answer);
    }

    public List<String> scanByFile(File fileBuffer) throws Exception {
        List<String> answer = new ArrayList<>();
        String host = "https://ocrapi-advanced.taobao.com";
        String path = "/ocrservice/advanced";
        String method = "POST";
        String appcode = "e7f40ff51eef4fe0b998f88f6f0512c0";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        byte[] buffer = new byte[(int)fileBuffer.length()];
        String base64Code=new BASE64Encoder().encode(buffer);
        String bodys =  "{\"img\":\""+ base64Code+"\",\"prob\":false}";
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            answer = prase(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answer;
    }

    @Override
    public List<List<String>> scanByUrls(String[] urls) {
        List<List<String>> dataList = new ArrayList<>();
        for (String url : urls) {
            dataList.add(scanByUrl(url));
        }
        return dataList;
    }

    public List<String> scanByUrl(String url){
//        String url = "https://blacktry.oss-cn-beijing.aliyuncs.com/2021/06/27/52bac197625943bf8da27bdf1bc901b9.jpg?versionId=CAEQEBiBgICZsaul0hciIDI3OTc0MmVjYTliYTQ4NjJiNDE4MzM4NmJjNGJiZTBm";
        List<String> answer = new ArrayList<>();
        String host = "https://ocrapi-advanced.taobao.com";
        String path = "/ocrservice/advanced";
        String method = "POST";
        //自己的appCode
        String appcode = "e7f40ff51eef4fe0b998f88f6f0512c0";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE ****************
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        String bodys = "{\"img\":\"\",\"url\":\""+url+"\",\"prob\":false,\"charInfo\":false,\"rotate\":false,\"table\":false}";

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
//            //获取response的body
//            System.out.println(EntityUtils.toString(response.getEntity()));
            answer = prase(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answer;
    }

    /**
     * 解析Json
     * @param string 获取response中的Json
     * @return
     */
    public List<String> prase(String string){
        List<String> answer = new ArrayList<>();
        JSONObject jsonObject=JSONObject.parseObject(string);
        JSONArray jsonArray=jsonObject.getJSONArray("prism_wordsInfo");
        for (int i=0;i<jsonArray.size();i++){
            JSONObject newjsonObject=(JSONObject) jsonArray.get(i);
            String word = newjsonObject.getString("word");
            System.out.println(word);
            answer.add(word);
        }
        return answer;
    }

}
